package cn.core.tool.interceptors;

import cn.core.tool.exception.CoreException;
import cn.core.tool.util.Res;
import com.zaxxer.hikari.pool.HikariPool;
import feign.FeignException;
import feign.RetryableException;
import feign.codec.DecodeException;
import lombok.extern.log4j.Log4j2;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常拦截器
 */
@Log4j2
@RestControllerAdvice
public class CoreExceptionHandler {

  @ExceptionHandler(Exception.class)
  public Res<?> exceptionHandler(HttpServletRequest request, Exception e) {
    if (log.isInfoEnabled()) {
      log.error(e.getMessage(), e);
    }
    return new Res<>().setException(CoreException.E_ERR);
  }

  @ExceptionHandler(CoreException.class)
  public Res<?> coreToolExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(((CoreException) e).getErrMsg());
  }

  @ExceptionHandler(DuplicateKeyException.class)
  public Res<?> duplicateKeyExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(CoreException.E_DATA_REPEAT_ERR);
  }

  @ExceptionHandler(DataIntegrityViolationException.class)
  public Res<?> dataIntegrityViolationExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(CoreException.E_DATA_IS_NULL_ERR);
  }

  @ExceptionHandler(HikariPool.PoolInitializationException.class)
  public Res<?> poolInitializationExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(CoreException.E_ADD_DATA_SOURCE_ERR);
  }

  @ExceptionHandler(RetryableException.class)
  public Res<?> retryableExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(CoreException.E_REQUEST_CANNOT_CONNECT);
  }

  @ExceptionHandler(FeignException.class)
  public Res<?> feignExceptionHandler(HttpServletRequest request, Exception e) {
    if (401 == ((FeignException) e).status()) {
      return new Res<>().setException(CoreException.E_REQUEST_UNAUTHORIZED);
    } else {
      return new Res<>().setException(CoreException.E_REQUEST_ERR);
    }
  }

  @ExceptionHandler(DecodeException.class)
  public Res<?> decodeExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(CoreException.E_REQUEST_RESPONSE_PARSE_FAILED);
  }

  @ExceptionHandler(MaxUploadSizeExceededException.class)
  public Res<?> maxUploadSizeExceededExceptionHandler(HttpServletRequest request, Exception e) {
    return new Res<>().setException(CoreException.E_UPLOAD_FILE_SIZE_EXCEEDS_THE_MAXIMUM_LIMIT);
  }

}
